
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>RabbitMQ交换机的类型有那些 - 交互式测验</title>
      <style>
        @import url('https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@400;500;700&display=swap');
        
        body {
          font-family: 'Noto Sans SC', sans-serif;
          background-color: #f4f7f9;
          color: #333;
          display: flex;
          justify-content: center;
          align-items: center;
          min-height: 100vh;
          margin: 0;
          padding: 20px;
          box-sizing: border-box;
        }
        
        .main-wrapper {
            position: relative;
            width: 100%;
            max-width: 900px; /* Wider to accommodate buttons */
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .quiz-container {
          background-color: #ffffff;
          border-radius: 16px;
          box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
          width: 100%;
          max-width: 700px;
          overflow: hidden;
          z-index: 10;
        }

        .quiz-header {
          background-color: #4a90e2;
          color: white;
          padding: 20px 30px;
          text-align: center;
        }

        .quiz-header h1 {
          margin: 0;
          font-size: 24px;
          font-weight: 700;
        }
        
        .quiz-header p {
            margin: 5px 0 0;
            font-size: 14px;
            opacity: 0.9;
        }

        .quiz-body {
          padding: 30px;
        }

        .progress-bar {
            display: none; /* 隐藏进度条 */
            width: 100%;
            background-color: #e0e0e0;
            border-radius: 5px;
            height: 10px;
            margin-bottom: 20px;
        }

        #progress-indicator {
            height: 100%;
            width: 0%;
            background-color: #4caf50;
            border-radius: 5px;
            transition: width 0.3s ease;
        }

        #question-container {
          margin-bottom: 20px;
        }

        #question-text {
          font-size: 18px;
          font-weight: 500;
          line-height: 1.6;
          margin-bottom: 25px;
        }

        .options-list {
          list-style: none;
          padding: 0;
          margin: 0;
        }

        .option-item {
          background-color: #f8f9fa;
          border: 1px solid #dee2e6;
          border-radius: 8px;
          padding: 15px;
          margin-bottom: 12px;
          cursor: pointer;
          transition: background-color 0.2s ease, border-color 0.2s ease;
        }

        .option-item:hover {
          background-color: #e9ecef;
        }
        
        .option-item.selected {
            background-color: #d1e7fd;
            border-color: #4a90e2;
        }

        .quiz-footer {
          padding: 20px 30px;
          display: flex;
          justify-content: space-between; /* 将按钮分布在两侧 */
          align-items: center;
          min-height: 65px; /* Reserve space */
        }

        .nav-btn {
          background-color: #4a90e2;
          color: white;
          border: none;
          border-radius: 8px;
          padding: 10px 20px;
          font-size: 16px;
          font-weight: 500;
          cursor: pointer;
          transition: background-color 0.2s ease, transform 0.2s ease;
          box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }
        
        #next-btn {
            background-color: #28a745;
        }

        .nav-btn:hover {
          background-color: #357abd;
          transform: scale(1.05);
        }
        
        .nav-btn:disabled {
            background-color: #a0c3e8;
            cursor: not-allowed;
            opacity: 0.7;
        }

        #result-container {
            border-top: 1px solid #eee;
        }
        
        .result-box {
            border-radius: 8px;
            padding: 20px;
            margin-top: 20px;
        }
        
        .result-box.correct {
            background-color: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
        }

        .result-box.incorrect {
            background-color: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
        }
        
        .result-box h3 {
            margin-top: 0;
        }

        .explanation-text {
            margin-top: 15px;
            line-height: 1.7;
        }
        
        .source-text {
            font-style: italic;
            font-size: 14px;
            margin-top: 15px;
            color: #555;
        }

        
        .final-score-container {
            padding: 40px;
            text-align: center;
        }
        .final-score-container h2 {
            margin-top: 0;
            margin-bottom: 30px;
        }
        .score-summary {
            display: flex;
            justify-content: center;
            gap: 20px;
            margin-bottom: 40px;
            flex-wrap: wrap;
        }
        .score-card {
            background-color: #f8f9fa;
            border-radius: 12px;
            padding: 20px;
            width: 180px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.05);
            border: 1px solid #e9ecef;
        }
        .score-card h3 {
            margin: 0 0 10px;
            font-size: 16px;
            font-weight: 500;
            color: #555;
        }
        .score-card p {
            margin: 0;
            font-size: 28px;
            font-weight: 700;
            color: #333;
        }
        .score-details table {
            width: 100%;
            font-size: 16px;
        }
        .score-details td {
            padding: 4px 0;
        }
        .score-details td:last-child {
            text-align: right;
            font-weight: 700;
        }
        .report-actions button {
            background-color: #fff;
            border: 1px solid #ccc;
            border-radius: 8px;
            padding: 12px 25px;
            font-size: 16px;
            cursor: pointer;
            margin: 0 10px;
            transition: background-color 0.2s ease, border-color 0.2s ease, transform 0.2s ease;
        }
        .report-actions button:hover {
            background-color: #f1f1f1;
            border-color: #bbb;
            transform: translateY(-2px);
        }
        .report-actions button.primary {
            background-color: #28a745;
            color: white;
            border-color: #28a745;
        }
        .report-actions button.primary:hover {
            background-color: #218838;
        }
        
        .hint-container {
            background-color: #e0f7fa;
            border: 1px solid #b2ebf2;
            border-radius: 8px;
            padding: 15px;
            margin-top: 20px;
            color: #006064;
            font-size: 15px;
            line-height: 1.6;
            display: none; /* 默认隐藏 */
        }
      </style>
    </head>
    <body>
      <div class="main-wrapper">
          <div class="quiz-container">
            <div class="quiz-header">
              <h1>RabbitMQ交换机的类型有那些 - 交互式测验</h1>
              <p>检验你对文档内容的理解程度</p>
            </div>
            <div id="quiz-content">
                <div class="quiz-body">
                    <div class="progress-bar">
                        <div id="progress-indicator"></div>
                    </div>
                    <div id="question-container">
                      <p id="question-text"></p>
                      <ul class="options-list" id="options-list"></ul>
                    </div>
                    <div id="result-container"></div>
                    <div id="hint-container" class="hint-container"></div>
                </div>
                <div class="quiz-footer" id="quiz-footer">
                  <button id="prev-btn" class="nav-btn">上一题</button>
                  <button id="hint-btn" class="nav-btn" style="background-color: #ffc107; color: #333; box-shadow: 0 4px 12px rgba(255,193,7,0.3);">提示</button>
                  <button id="next-btn" class="nav-btn">下一题</button>
                </div>
            </div>
          </div>
      </div>

      <script>
        const quizData = [
  {
    "question": "在RabbitMQ中，交换机（Exchange）扮演的核心角色是什么？",
    "options": [
      "作为消息的最终存储单元，消费者直接从交换机拉取消息。",
      "管理消费者的网络连接，确保消费者始终在线。",
      "接收来自生产者的消息，并根据特定的路由规则将其分发到一个或多个队列中，实现解耦。",
      "直接将消息持久化到磁盘，以防止数据丢失。"
    ],
    "correctAnswerIndex": 2,
    "explanation": "交换机是RabbitMQ消息路由机制的核心。它作为生产者和消费者之间的中间层，接收生产者发送的消息，并根据绑定规则和路由键将消息分发到相应的队列。这个过程实现了生产者与消费者的解耦，提高了系统的灵活性和可维护性。",
    "source": "文档中「交换机在消息路由中的作用」及「3. 解耦生产者和消费者」部分",
    "hint": "文档提到：\"交换机在生产者和消费者之间起到了解耦的作用。生产者只需要将消息发送到交换机，不需要关心消息最终到达的队列或消费者。\""
  },
  {
    "question": "如果一个系统需要将一条消息（例如，系统更新通知）广播给所有订阅了该消息的消费者，最适合使用哪种类型的交换机？",
    "options": [
      "Direct Exchange，因为它能精确地将消息发送到指定队列。",
      "Topic Exchange，因为它支持复杂的模式匹配路由。",
      "Fanout Exchange，因为它会将消息广播到所有绑定的队列，并忽略路由键。",
      "Headers Exchange，因为它能基于消息头进行灵活路由。"
    ],
    "correctAnswerIndex": 2,
    "explanation": "Fanout Exchange 采用广播机制，它会将接收到的任何消息都分发给所有与之绑定的队列，完全不考虑路由键。这完全符合“发布-订阅”模式中将消息广播给所有订阅者的需求。",
    "source": "文档中「Fanout Exchange」部分",
    "hint": "文档中对该交换机的描述是：\"将接收到的消息广播给所有绑定到它的队列，不考虑路由键。这种方式适用于需要将消息广播给多个消费者的场景，如发布订阅模式。\""
  },
  {
    "question": "假设一个Topic Exchange上有一个队列，其绑定键（Binding Key）为 `log.*.error`。下列哪个路由键（Routing Key）的消息会被成功路由到这个队列？",
    "options": [
      "log.auth.critical.error",
      "log.error",
      "auth.error",
      "log.database.error"
    ],
    "correctAnswerIndex": 3,
    "explanation": "在Topic Exchange的模式匹配中，`*` (星号) 匹配一个单词。路由键 `log.database.error` 与绑定键 `log.*.error` 能够匹配，因为 `database` 恰好匹配了 `*` 的位置。而 `log.auth.critical.error` 需要用 `#` 来匹配中间的两个单词；`log.error` 则缺少了一个单词。",
    "source": "文档中「Topic Exchange」部分",
    "hint": "请回想 `*` 和 `#` 这两个特殊字符在Topic Exchange绑定键中的具体含义。其中一个匹配单个单词，另一个匹配零个或多个单词。"
  },
  {
    "question": "Headers Exchange与其他交换机最根本的区别在于它的路由决策依据是什么？",
    "options": [
      "消息的路由键（Routing Key）的模式匹配结果。",
      "消息头（Headers）中的一组键值对属性。",
      "消息的优先级（Priority）属性。",
      "消息体（Body）的内容。"
    ],
    "correctAnswerIndex": 1,
    "explanation": "Headers Exchange的路由机制是独特的，它完全不依赖于路由键。相反，它检查消息头（Headers）中的属性。队列在绑定到Headers Exchange时会定义一组键值对匹配规则，交换机根据这些规则以及`x-match`参数（'all'或'any'）来决定消息的去向。",
    "source": "文档中「Headers Exchange」部分",
    "hint": "文档明确指出：\"Headers Exchange根据消息头中的属性（Headers）进行路由，而不是路由键。\""
  },
  {
    "question": "为了确保RabbitMQ在单个节点故障后消息不丢失且服务能够继续，文档中提到的关键高可用性机制是什么？",
    "options": [
      "备份交换机（Alternate Exchange），用于处理无法路由的消息。",
      "生产者确认（Publisher Confirms），用于确保消息到达交换机。",
      "镜像队列（Mirrored Queues），它将队列消息复制到集群中的多个节点。",
      "消息的TTL（Time-To-Live），用于自动清理过期消息。"
    ],
    "correctAnswerIndex": 2,
    "explanation": "镜像队列是RabbitMQ提供的一种核心高可用性机制。它通过在集群内的多个节点上创建队列的副本（镜像）来工作。当持有主队列的节点发生故障时，系统会自动将一个镜像节点提升为新的主节点，从而保证了服务的连续性和消息的冗余，防止因单点故障导致数据丢失。",
    "source": "文档中「镜像队列」部分",
    "hint": "文档中描述了某种机制：\"通过将队列中的消息镜像到集群中的多个节点来实现...如果主节点发生故障，RabbitMQ 会自动切换到一个镜像节点继续提供服务。\""
  },
  {
    "question": "在何种场景下，Direct Exchange 是最合适的选择？",
    "options": [
      "需要根据消息的多个非字符串属性（如格式、类型）进行复杂路由。",
      "需要将消息广播给系统中的所有订阅者。",
      "需要根据任务类型或优先级，将消息精确地路由到特定的处理队列。",
      "需要根据主题（如`news.sports.basketball`）进行多级分类和订阅。"
    ],
    "correctAnswerIndex": 2,
    "explanation": "Direct Exchange 的核心机制是精确匹配。它将消息的路由键与队列的绑定键进行完全匹配的比较。这种机制非常适用于需要将消息精确地、一对一或一对多地发送到指定队列的场景，例如任务分发系统，可以根据任务类型（作为路由键）分发到不同的工作队列。",
    "source": "文档中「Direct Exchange」的「应用场景」部分",
    "hint": "思考一下哪种交换机的特点是\"精确匹配\"。文档的应用场景中提到了\"任务分发系统\"和\"点对点消息传递\"。"
  },
  {
    "question": "为了防止RabbitMQ服务器重启导致消息丢失，需要进行持久化设置。根据文档，以下哪项组合是实现消息被可靠保存所必需的？",
    "options": [
      "将交换机、队列和消息三者都设置为持久化。",
      "仅将消息设置为持久化（deliveryMode=2）。",
      "仅将交换机和队列设置为持久化。",
      "仅将队列设置为持久化。"
    ],
    "correctAnswerIndex": 0,
    "explanation": "要实现消息的真正持久化，防止在RabbitMQ重启时丢失数据，必须确保整个消息传递路径上的关键组件都是持久化的。这包括：1. 交换机本身必须是持久化的；2. 队列必须是持久化的；3. 消息在发送时必须被标记为持久化（deliveryMode=2）。缺少任何一环都可能导致在重启过程中丢失消息。",
    "source": "文档中「消息持久化」部分",
    "hint": "文档分别介绍了持久化交换机、持久化队列和持久化消息。思考一下，如果消息要从一个持久化的生产者安全到达一个持久化的消费者，中间环节是否也需要持久化？"
  }
];
        console.log("Quiz Data:", JSON.parse(JSON.stringify(quizData))); // 添加这行用于调试，以可展开的JSON格式输出
        
        let currentQuestionIndex = 0;
        let score = 0;
        // 存储每个问题的回答状态
        const userAnswers = new Array(quizData.length).fill(null); 

        const questionTextEl = document.getElementById('question-text');
        const optionsListEl = document.getElementById('options-list');
        const resultContainerEl = document.getElementById('result-container');
        const quizContentEl = document.getElementById('quiz-content');
        const progressIndicatorEl = document.getElementById('progress-indicator');
        const prevBtn = document.getElementById('prev-btn');
        const nextBtn = document.getElementById('next-btn');
        const hintBtn = document.getElementById('hint-btn');
        const hintContainerEl = document.getElementById('hint-container');

        function loadQuestion() {
          resultContainerEl.innerHTML = '';
          optionsListEl.innerHTML = '';
          hintContainerEl.style.display = 'none'; // 隐藏提示
          
          if (currentQuestionIndex >= quizData.length) {
            showFinalScore();
            return;
          }

          updateProgress();

          const currentQuestion = quizData[currentQuestionIndex];
          questionTextEl.textContent = `(${currentQuestionIndex + 1}/${quizData.length}) ${currentQuestion.question}`;
          
          currentQuestion.options.forEach((optionText, index) => {
            const li = document.createElement('li');
            li.className = 'option-item';
            li.textContent = optionText;
            li.dataset.index = index; // Store index in a data attribute
            // 如果这道题已经回答过，恢复状态
            if (userAnswers[currentQuestionIndex] !== null) {
                if (index === userAnswers[currentQuestionIndex]) {
                    li.classList.add('selected');
                }
            }
            optionsListEl.appendChild(li);
          });

          // 如果已经回答过，直接显示结果
          if (userAnswers[currentQuestionIndex] !== null) {
              const isCorrect = userAnswers[currentQuestionIndex] === currentQuestion.correctAnswerIndex;
              showResult(isCorrect, currentQuestion);
          }
          
          updateNavigationButtons();
          updateProgress();
        }

        function selectOption(optionIndex) {
            userAnswers[currentQuestionIndex] = optionIndex;
            const currentQuestion = quizData[currentQuestionIndex];
            const isCorrect = optionIndex === currentQuestion.correctAnswerIndex;

            // 重新计算分数
            score = userAnswers.reduce((acc, answer, index) => {
                return answer === quizData[index].correctAnswerIndex ? acc + 1 : acc;
            }, 0);

            showResult(isCorrect, currentQuestion);
            updateNavigationButtons();
        }
        
        function updateProgress() {
            const answeredQuestions = userAnswers.filter(answer => answer !== null).length;
            const progressPercentage = (answeredQuestions / quizData.length) * 100;
            progressIndicatorEl.style.width = `${progressPercentage}%`;
        }
        
        function updateNavigationButtons() {
            prevBtn.style.display = 'block';
            nextBtn.style.display = 'block';
            hintBtn.style.display = 'block'; // 显示提示按钮

            prevBtn.disabled = currentQuestionIndex === 0;
            nextBtn.disabled = false; // 最后一题时，下一题按钮不禁用，而是用于显示报告
            nextBtn.textContent = (currentQuestionIndex === quizData.length - 1) ? '查看报告' : '下一题';
            
            // 如果当前问题没有提示，则禁用提示按钮并隐藏提示内容
            if (!quizData[currentQuestionIndex].hint) {
                hintBtn.disabled = true;
                hintContainerEl.style.display = 'none';
                hintContainerEl.textContent = ''; // 清除旧的提示内容
            } else {
                hintBtn.disabled = false;
            }
        }

        function showResult(isCorrect, questionData) {
            resultContainerEl.innerHTML = ''; // 清空之前的结果
            const resultBox = document.createElement('div');
            resultBox.className = `result-box ${isCorrect ? 'correct' : 'incorrect'}`;
            
            let html = `<h3>${isCorrect ? '回答正确！' : '回答错误'}</h3>`;
            if (!isCorrect) {
                html += `<p><strong>正确答案是：</strong> ${questionData.options[questionData.correctAnswerIndex]}</p>`;
            }
            html += `<div class="explanation-text">${questionData.explanation}</div>`;
            html += `<div class="source-text">来源: ${questionData.source}</div>`;
            
            resultBox.innerHTML = html;
            resultContainerEl.appendChild(resultBox);

            // 禁用所有选项的点击事件，并高亮正确/错误答案
            Array.from(optionsListEl.children).forEach((child, index) => {
                child.style.pointerEvents = 'none';
                // 高亮正确答案
                if (index === questionData.correctAnswerIndex) {
                    child.classList.add('correct'); // 需要添加CSS样式
                    child.style.backgroundColor = '#d4edda';
                    child.style.borderColor = '#c3e6cb';
                }
                // 如果选错了，高亮错误选项
                if (!isCorrect && index === userAnswers[currentQuestionIndex]) {
                    child.classList.add('incorrect'); // 需要添加CSS样式
                    child.style.backgroundColor = '#f8d7da';
                    child.style.borderColor = '#f5c6cb';
                }
            });
        }

        function goToNextQuestion() {
            if (currentQuestionIndex < quizData.length - 1) {
                currentQuestionIndex++;
                loadQuestion();
            } else {
                showFinalScore();
            }
        }

        function goToPreviousQuestion() {
            if (currentQuestionIndex > 0) {
                currentQuestionIndex--;
                loadQuestion();
            }
        }
        
        function showHint() {
            const currentQuestion = quizData[currentQuestionIndex];
            if (currentQuestion.hint) {
                hintContainerEl.textContent = currentQuestion.hint;
                hintContainerEl.style.display = 'block';
            } else {
                hintContainerEl.style.display = 'none';
            }
        }

        function showFinalScore() {
            document.querySelector('.quiz-body').style.display = 'none';
            document.getElementById('quiz-footer').style.display = 'none';

            const correctCount = score;
            const totalQuestions = quizData.length;
            const answeredCount = userAnswers.filter(a => a !== null).length;
            const wrongCount = answeredCount - correctCount;
            const skippedCount = totalQuestions - answeredCount;
            const accuracy = totalQuestions > 0 ? Math.round((correctCount / totalQuestions) * 100) : 0;
            const errorRate = totalQuestions > 0 ? Math.round((wrongCount / totalQuestions) * 100) : 0;

            const finalScoreHtml =
                '<div class="final-score-container">' +
                '<h2>答题报告</h2>' +
                '<div class="score-summary">' +
                '<div class="score-card">' +
                '<h3>得分</h3>' +
                '<p>' + correctCount + ' / ' + totalQuestions + '</p>' +
                '</div>' +
                '<div class="score-card">' +
                '<h3>正确率</h3>' +
                '<p>' + accuracy + '%</p>' +
                '</div>' +
                '<div class="score-card">' +
                '<h3>错误率</h3>' +
                '<p>' + errorRate + '%</p>' +
                '</div>' +
                '<div class="score-card score-details">' +
                '<table>' +
                '<tr><td>正确</td><td>' + correctCount + '</td></tr>' +
                '<tr><td>错误</td><td>' + wrongCount + '</td></tr>' +
                '<tr><td>未答</td><td>' + skippedCount + '</td></tr>' +
                '</table>' +
                '</div>' +
                '</div>' +
                '<div class="report-actions">' +
                '<button id="review-btn">回顾测验</button>' +
                '<button class="primary" onclick="location.reload()">再试一次</button>' +
                '</div>' +
                '</div>';

            let reportEl = document.querySelector('.final-score-container');
            if (reportEl) {
                reportEl.remove();
            }
            quizContentEl.insertAdjacentHTML('beforeend', finalScoreHtml);
            document.getElementById('review-btn').addEventListener('click', reviewQuiz);
        }

        function reviewQuiz() {
            const reportEl = document.querySelector('.final-score-container');
            if (reportEl) {
                reportEl.remove();
            }

            document.querySelector('.quiz-body').style.display = 'block';
            document.getElementById('quiz-footer').style.display = 'flex';
            
            currentQuestionIndex = 0;
            loadQuestion();
            updateNavigationButtons(); // Ensure nav buttons are correctly displayed
        }

        // Event Delegation for options
        optionsListEl.addEventListener('click', (event) => {
            if (event.target && event.target.matches('li.option-item')) {
                // Check if the question has already been answered
                if (userAnswers[currentQuestionIndex] === null) {
                    const selectedIndex = parseInt(event.target.dataset.index, 10);
                    selectOption(selectedIndex);
                }
            }
        });

        prevBtn.addEventListener('click', goToPreviousQuestion);
        nextBtn.addEventListener('click', goToNextQuestion);
        hintBtn.addEventListener('click', showHint);
        
        // 初始加载
        loadQuestion();
      </script>
    </body>
    </html>
  